package com.freshmarket.freshmarket.realm;

import com.freshmarket.freshmarket.dao.AuthoMapper;
import com.freshmarket.freshmarket.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

@Slf4j
public class CustomRealm extends AuthorizingRealm {
    @Resource
    private AuthoMapper authoMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("当前用户为:{}" + authenticationToken.getPrincipal());

        User user = authoMapper.findByUserPhone((String) authenticationToken.getPrincipal());

        if (user == null) {
            throw new UnknownAccountException();
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getUserPassword(), getName());
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("user", user);
        return simpleAuthenticationInfo;
    }
}
